package webmote.server;

import java.awt.AWTException;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;

import webmote.client.Constants;
import webmote.client.RemoteScreen;
import webmote.client.ScreenSize;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RemoteScreenServlet extends RemoteServiceServlet implements RemoteScreen, Constants {

	private static final long serialVersionUID = -8297187492194119190L;

	public ScreenSize getSize() {
        Rectangle screenSize = getDefaulScreenDevice().getDefaultConfiguration().getBounds();
        return new ScreenSize(screenSize.width, screenSize.height);
    }

    public int[][] getTilesIds() {
        Robot robot = createRobot();
        Rectangle screenSize = getDefaulScreenDevice().getDefaultConfiguration().getBounds();
        
        int imageWidth = screenSize.width % TILE_SIZE == 0 ? screenSize.width : (screenSize.width / TILE_SIZE + 1) * TILE_SIZE; 
        int imageHeight = screenSize.height % TILE_SIZE == 0 ? screenSize.height : (screenSize.height / TILE_SIZE + 1) * TILE_SIZE; 
        BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_USHORT_565_RGB);

        Graphics2D graphics = bufferedImage.createGraphics();
        graphics.drawImage(robot.createScreenCapture(screenSize), 0, 0, null);
        graphics.dispose();
        
        SessionImages sessionImages = SessionImages.getSessionImages(getThreadLocalRequest().getSession());
        sessionImages.setScreenCapture(bufferedImage);
        
        return sessionImages.getTilesIds();
    }
    
    private GraphicsDevice getDefaulScreenDevice() {
        return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    }

    private Robot createRobot() {
        try {
            return new Robot(getDefaulScreenDevice());
        } catch (AWTException e) {
            throw new IllegalStateException("Cannot create robot!");
        }
    }
    
}
